package com.android.djlmapp.activity.kuandai.web;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.http.ComPareUtils;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.token.GetUrlStr;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.view.WebView4Scroll;
import com.gyf.barlibrary.ImmersionBar;
import com.just.agentweb.AgentWeb;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 宽带套餐详情
 */
public class KuanDaiTcDetailsActivity extends AppCompatActivity {
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.webviewframe)
    RelativeLayout webviewFrame;
    @BindView(R.id.web_swiperefreshlayout)
    SwipeRefreshLayout mswiperefreshlayout;

    private AgentWeb mAgentWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        ButterKnife.bind(this);

        initView();
        initData();
        // 沉浸式
        initImmersionBar();
    }

    /**
     * 沉浸式状态栏初始化
     */
    private void initImmersionBar() {
        ImmersionBar.with(this)
                .keyboardEnable(true)
                .navigationBarWithKitkatEnable(false)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色;
                .statusBarColor(R.color.homeWhite)
                .init();
    }

    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }

    private void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.GONE);
        tvName.setText("套餐详情");
    }

    private void initData() {
        UserInfoUtils userInfoUtilsInstance = UserInfoUtils.getUserInfoUtilsInstance();
        String spcid = getIntent().getStringExtra("SPCID");
        String signUrl = new ComPareUtils.ComPareBuilder()
                .put("spec_id", spcid)
                .put("token", userInfoUtilsInstance.getToken())
                .put("version", userInfoUtilsInstance.getVersion())
                .create().getSignString();

        String url = GlobalUrls.TC_DETAILS + "?spec_id=" + spcid
                + "&token=" + userInfoUtilsInstance.getToken() +
                "&version=" + userInfoUtilsInstance.getVersion() + "&sign=" + signUrl;

        if (mAgentWeb == null) {
            WebView4Scroll webView4Scroll = new WebView4Scroll(KuanDaiTcDetailsActivity.this, mswiperefreshlayout);
            webView4Scroll.setVerticalScrollBarEnabled(false);
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(webviewFrame, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebView(webView4Scroll)
                    .setWebViewClient(mWebViewClient)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .createAgentWeb()
                    .ready()
                    .go(url);

            mAgentWeb.getAgentWebSettings().getWebSettings().setGeolocationEnabled(false);
        } else {
            mAgentWeb.getUrlLoader().reload();
        }
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String str) {
            if (str.contains("login_out")) {
                GetUrlStr.getStrUrl(KuanDaiTcDetailsActivity.this);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, str);
        }

        @SuppressLint("NewApi")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String str = request.getUrl().toString();
            if (str.contains("login_out")) {
                GetUrlStr.getStrUrl(KuanDaiTcDetailsActivity.this);
                return true;
            }
            return false;
        }
    };

    @OnClick(R.id.ll_top_back)
    public void onViewClicked() {
        if (mAgentWeb.back()) {
            mAgentWeb.back();
        } else {
            setResult(RESULT_OK, new Intent());
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.back()) {
            mAgentWeb.back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    //设置android app 的字体大小不受系统字体大小改变的影响
    @Override
    public Resources getResources() {
        Resources res = null;
        try {
            res = super.getResources();
            Configuration config = new Configuration();
            config.setToDefaults();
            res.updateConfiguration(config, res.getDisplayMetrics());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("项目异常", "--onLivenessSuccess----getResources------" + e.toString());
        }
        return res;
    }
    @Override
    protected void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.destroy();
        }
        ImmersionBar.with(this).destroy();
        super.onDestroy();
    }
}
